package weibo4j.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

import weibo4j.Configuration;

public class DebugPrn implements Serializable {
    private final static boolean DEBUG = Configuration.getDebug();
    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    private static LogStream log = getLog();
    private StringBuffer sb = new StringBuffer();
    private String name;

    public DebugPrn(String name) {
        this.name = '[' + name + ']';
    }

    private static LogStream getLog() {
        try {
            String strFile = "C://weibo.log";
            File file = new File(strFile);
            if (file.isFile()) {
                file.delete();
            }
            return new LogStream(strFile);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public void info(Object message) {
        info(message, null);
    }

    public void info(Object message, Throwable t) {
        if (DEBUG) {
            if (message instanceof Throwable) {
                sb.append(sdf.format(new Date())).append(" INFO ").append(name).append(' ').append(((Throwable) message).getMessage());
            } else {
                sb.append(sdf.format(new Date())).append(" INFO ").append(name).append(' ').append(message);
            }
            if (t != null && log != null) {
                t.printStackTrace(log);
                sb.append('\n').append(log.toString());
            }
            System.out.println(sb.toString());
            log.println(sb.toString());
        }
        sb.setLength(0);
    }

    public void error(Object message) {
        error(message, null);
    }

    public void error(Object message, Throwable t) {
        if (DEBUG) {
            if (message instanceof Throwable) {
                sb.append(sdf.format(new Date())).append(" INFO ").append(name).append(' ').append(((Throwable) message).getMessage());
            } else {
                sb.append(sdf.format(new Date())).append(" INFO ").append(name).append(' ').append(message);
            }
            if (t != null && log != null) {
                t.printStackTrace(log);
                sb.append('\n').append(log.getString());
            }
            System.err.println(sb.toString());
            log.println(sb.toString());
        }
        sb.setLength(0);
    }
}